﻿//USER GRID SPECIFIC LOGIC
var addNewWorkspace;


columnNames = ["", "ID", "ClientID", "Display Name", "First Name", "Last Name", "Phone", "Email", "Role", "Created Date", "Created By"];
columnModel =
[
    { "name": "Edit", "index": "Edit", "width": 20, "height": 20, "align": "left", "hidedlg": true, "fixed": true, "search": false, "classes": "editrow", "title": true, "hidden": false, "widthOrg": 20, "resizable": true, "sortable": true, "stype": "text" },
    { "name": "pkUser_ID", "index": "pkUser_ID", "width": 1, "editable": false, "hidedlg": true, "hidden": true, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "fkClient_ID", "index": "fkClient_ID", "width": 1, "editable": false, "hidedlg": true, "hidden": true, "title": true, "widthOrg": 1, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "DisplayName", "index": "DisplayName", "width": 80, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "FirstName", "index": "Firstname", "width": 90, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "LastName", "index": "Lastname", "width": 90, "editable": false, "hidden": false, "title": true, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "Phone1", "index": "Phone1", "width": 100, "align": "center", "editable": false, "hidden": false, "title": true, "widthOrg": 100, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "Email", "index": "Email", "width": 160, "editable": false, "hidden": false, "title": true, "widthOrg": 100, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "ClientRoleName", "index": "UserRoleName", "width": 100, "align": "left", "editable": false, "hidden": false, "title": true, "widthOrg": 60, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedOn", "index": "CreatedDate", "width": 80, "align": "center", "editable": false, "title": true, "hidden": false, "widthOrg": 80, "resizable": true, "sortable": true, "search": true, "stype": "text" },
    { "name": "CreatedBy", "index": "CreatedBy", "width": 80, "align": "center", "editable": false, "hidden": false, "searchoptions": {}, "title": true, "widthOrg": 40, "resizable": true, "sortable": true, "search": true, "stype": "text" }
];


$(document).ready(function () {

    
    
    $('#userTab').attr('class', 'navon').children('span').attr('class', 'navspanon');

    //PRIVATE FUNCTIONS
    var showDetailNoNav;
    var fillClientRoles;

    //PRIVATE VARIABLES    
    var intrnl = false;
    var isloaded = false;
    var selRow;
    var gridRow;
    var grid = jQuery("#list");
    var glasswrapper = $('#glasswrapper');
    var overridepage = 0; //i need this for the resize column functionality.
    var gridconfigtype = 'UserGrid';
    $('#resubmitter').dialog({ autoOpen: false, minWidth: 475, minHeight: 240, resizable: false, close: function(event, ui) { glasswrapper.hide(); } });

    //GetVCConfig();
    
    //EVENTS
    $('.detailcancel').click(function () {
        frmvisualvalid = $('#frmuserdetails').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
        $('#frmuserdetails').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
        $('#frmuserdetails').stop().find('.jValSpacer,.jValSpacercover').stop().remove().end();
        CancelClick();
        //$('#detailform').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
        return false;
    }),
    
    $('.detaildelete').click(function () {
        DeactivateUser();
        return false;
    }),
    
    $('.detailsave').click(function () {
        SaveUser();
        return false;
    }),
    
    $('.detailadd').click(function () {
        SaveNewUser();
        return false;
    }),
    $('#up_ResetPass').click(function () {
        var resp = confirm("Resetting the user password sends an email notification to the user with a new temporary password and a login link. The email also provides instructions on how to create a new permanent password. \n\nPlease click OK to confirm.");
        if (resp) {
            ResetPassword($('#display_email').html(), 'Forced');
        }
        return false;
    }),


    $(".form_table input:checkbox").click(function () {
        promptSave();
    }),
    
    $('.form_txt').keydown(function () {
        promptSave();
    }),
    
    $('.form_txtarea').keydown(function () {
        promptSave();
    }),
    
    $('.form_select').change(function () {
        promptSave();
    }),


    showDetailNoNav = function() {
        $('#panel_grid_main').hide();
        $('#panel_grid_sub').show();
        $('#panel_tabs').show();
        //        canvasheight = $('#site_top_middle').height();
        //        loader.css({ height: canvasheight - 182, width: canvaswidth });
        preSave(intrnl);
        try {
            var containerwidth = $('#second_grid_container').width();
            $('#second_list').jqGrid('setGridWidth', containerwidth - 2);
        } catch(err) {

        }
    };

    //FORM
    
    
    var FillUserForm = function (rowdata) {
        ShowDetailNoNav();
        $('.detailadd').hide();
        $('.detailsave').show();
        $('.detaildelete').show();
        $('.notnew').show();
        $('.isnew').hide();
        fillClientRoles(rowdata.ClientRoleName);
        $('#hidID').val(rowdata.pkUser_ID);

        $('#user_email').val('');
        $('#user_email').hide();
        $('#display_email').html(rowdata.Email);
        $('#user_firstname').val(rowdata.FirstName);
        $('#user_lastname').val(rowdata.LastName);
        //$('#user_organization').val(rowdata.Organization);
        $('#user_role').val(rowdata.ClientRoleName);
        $('#user_title').val(rowdata.Title);
        $('#user_phone1').val(rowdata.Phone1);
        $('#user_phone2').val(rowdata.Phone2);
        $('#user_address1').val(rowdata.Address1);
        $('#user_address2').val(rowdata.Address2);
        $('#user_city').val(rowdata.City);
        $('#user_zipcode').val(rowdata.PostalCode);
        $('#user_state').val(rowdata.StateProv);
        $('#user_country').val(rowdata.Country);
        if (rowdata.IsCurrent) {
            $('.detaildelete').button("option", "disabled", true);
        }
        else {
            $('.detaildelete').button("option", "disabled", false);
        }

    };
    var FillGridRowClass = function () {
        var isvalid = true;
        var gridRow = new Object();
        gridRow.ClientRoleName = '';
        gridRow.Email = '';

        gridRow.pkUser_ID = $('#hidID').val();
        gridRow.FirstName = $('#user_firstname').val();
        gridRow.LastName = $('#user_lastname').val();
        gridRow.ClientRoleName = $('#user_role').val();
        gridRow.Title = $('#user_title').val();
        gridRow.Phone1 = $('#user_phone1').val();
        gridRow.Phone2 = $('#user_phone2').val();
        gridRow.Address1 = $('#user_address1').val();
        gridRow.Address2 = $('#user_address2').val();
        gridRow.City = $('#user_city').val();
        gridRow.PostalCode = $('#user_zipcode').val();
        gridRow.StateProv = $('#user_state').val();
        gridRow.Country = $('#user_country').val();
        if ($('#display_email').html().length > 0) {
            gridRow.Email = $('#display_email').html();
        }
        if ($('#user_email').val().length > 0) {
            gridRow.Email = $('#user_email').val();
        }

        //validation
        if (gridRow.FirstName.length < 1) {
            isvalid = false;
        }
        if (gridRow.LastName.length < 1) {
            isvalid = false;
        }
        if (gridRow.Email.length > 1) {
            var rege = /^([a-zA-Z0-9.!#$%&*+-/=?\^_`{|}~-]+@[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*)$/;
            if (!rege.test(gridRow.Email)) {
                isvalid = false;
            }
        }
        else{
            isvalid = false;
        }
        if (gridRow.Phone1.length < 1) {
            isvalid = false;
        }
        if (gridRow.ClientRoleName==null || gridRow.ClientRoleName.length < 1) {
            isvalid = false;
        }

        if (!isvalid) {
            gridRow.valid = false;
        }
        return gridRow;
    };

    addNewUser = function() {
        
        var hidsearchid = $('#hidsearchid').val();
        //var hidsearchid = $('#txtSid').val();
        intrnl = true;
        var paramstring = '{seid:"' + hidsearchid + '", key:0, intrnl:' + intrnl + '}';
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Service/Services.aspx/AddRecentDetail",
            data: paramstring,
            dataType: "json",
            success: function(data, textStatus) {

            },
            error: function(data, textStatus) {
                //alert('An error has occured retrieving data!');
            }
        });

        //clear form
        $('#hidID').val('0');
        fillClientRoles('');
        ShowDetailNoNav();
        $('.isnew').show();
        $('#user_email').show();
        $('#user_email').val('');
        $('#display_email').html('');
        $('#user_firstname').val('');
        $('#user_lastname').val('');
        $('#user_role').val('');
        $('#user_title').val('');
        $('#user_phone1').val('');
        $('#user_phone2').val('');
        $('#user_address1').val('');
        $('#user_address2').val('');
        $('#user_city').val('');
        $('#user_zipcode').val('');
        $('#user_state').val('');
        $('#user_country').val('');

        $('.detailadd').show();
        $('.detailsave').hide();
        $('.detaildelete').hide();
        $('.notnew').hide();
        $('#user_email').focus();
        preSave();
    },
    EditUser = function(rowId) {
        selRow = rowId;
        jQuery('#list').setSelection(selRow);
        intrnl = true;
        gridRow = jQuery("#list").getRowData(rowId);
        var hidsearchid = $('#hidsearchid').val();
        //var hidsearchid = $('#txtSid').val();
        var paramstring = '{seid:"' + hidsearchid + '", key:' + gridRow.pkUser_ID + ', intrnl:true}';
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Service/Services.aspx/AddRecentDetail",
            data: paramstring,
            dataType: "json",
            success: function(data, textStatus) {

            },
            error: function(data, textStatus) {
                //alert('An error has occured retrieving data!');
            }
        });

        $('#hidID').val(gridRow.pkUser_ID);
        $('#loaderwrapper').show();
        FillUserForm(gridRow);
        $('#loaderwrapper').hide();

    },    
    ResetPassword = function(email, origination) {
        var params = '{email:"' + email + '", origination:"' + origination + '"}';
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Service/Services.aspx/ResetPassword",
            data: params,
            dataType: "json",
            success: function(data, textStatus) {

                var jsonresult = jQuery.parseJSON(data.d);
                if(jsonresult.errorMessage == ''){
                    alert('Reset sucessfully');

                }
                //Reset password successfully
            },
            error: function(data, textStatus) {
                //alert('An error has occured retrieving data!');
            }
        });
    },
    SaveNewUser = function() {
        var keepgoing = false
        gridRow = FillGridRowClass();
        var frmvisualvalid = false;
        frmvisualvalid = $('#frmuserdetails').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
        if (frmvisualvalid) {
            if (gridRow.valid == null) {
                var params = '{json:' + JSON.stringify(gridRow) + '}';
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/Service/Services.aspx/AddUser",
                    data: params,
                    dataType: "json",
                    success: function(data, textStatus) {
                        var msg = jQuery.parseJSON(data.d);
                        if (msg.ReturnCode >= 0) {
                            postSave();
                            $("#list").trigger("reloadGrid");
                            alert('User successfully created.');
                            var ids = grid.jqGrid('getDataIDs');
                            for (var i = 0; i < ids.length; i++) {
                                var rowId = ids[i];
                                gridRow = jQuery("#list").getRowData(rowId);
                                if (gridRow.pkUser_ID == msg.Message) {
                                    i = ids.length;
                                    EditUser(rowId);
                                }
                            }
                            ResetPassword(gridRow.Email, 'New');

                            CancelClick();
                        } else {
                            alert(msg.Message);
                        }


                    },
                    error: function(data, textStatus) {
                        //alert('An error has occured retrieving data!');
                    }
                });
                keepgoing = true;
            }
        }
        if (!keepgoing) {
            alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
        }
    },    
    SaveUser = function() {
        var keepgoing = false;
        gridRow = FillGridRowClass();
        var frmvisualvalid = false;
        frmvisualvalid = $('#frmuserdetails').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
        if (frmvisualvalid) {
            if (gridRow.valid == null) {
                $('#loaderwrapper').show();
                var params = '{json:' + JSON.stringify(gridRow) + '}';
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/Service/Services.aspx/UpdateUser",
                    data: params,
                    dataType: "json",
                    success: function(data, textStatus) {
                        var msg = jQuery.parseJSON(data.d);
                        if (msg.ReturnCode >= 0) {
                            jQuery('#list').setRowData(selRow, gridRow);
                            $("#list").trigger("reloadGrid");
                            postSave();
                            EditUser(selRow);
                            alert('User successfully updated.');
                        } else {
                            alert(msg.Message);
                        }
                        $('#loaderwrapper').hide();
                    },
                    error: function(data, textStatus) {
                        //alert('An error has occured retrieving data!');
                        $('#loaderwrapper').hide();
                    }
                });
                keepgoing = true;
            }
        }
        if (!keepgoing) {
            alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
            $('#loaderwrapper').hide();
        }
    },
    DeactivateUser = function() {
        var reslt = confirm("This action will deactivate this user and remove them from view.  Are you sure you want to proceed?");
        if (reslt) {
            var keepgoing = false
            gridRow = FillGridRowClass();
            gridRow.IsActive = false;
            var frmvisualvalid = false;
            frmvisualvalid = $('#frmuserdetails').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
            if (frmvisualvalid) {
                if (gridRow.valid == null) {
                    var params = '{json:' + JSON.stringify(gridRow) + '}';
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Service/Services.aspx/UpdateUser",
                        data: params,
                        dataType: "json",
                        success: function(data, textStatus) {
                            if (textStatus == "success") {
                                jQuery('#list').setRowData(selRow, gridRow)
                                $("#list").trigger("reloadGrid");
                                postSave();
                                CancelClick();
                            }
                        },
                        error: function(data, textStatus) {
                            //alert('An error has occured retrieving data!');
                        }
                    });
                    keepgoing = true;
                }
            }
            if (!keepgoing) {
                alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
            }
        }
    };
    promptSave = function() {
        //$('').attr('disabled', true);
        $('.detailadd').button("option", "disabled", false);
        $('.detailsave').button("option", "disabled", false);
        $('.detailcancel').button("option", "label", "Cancel");
    };
    preSave = function() {
        $('.detailadd').button("option", "disabled", true);
        $('.detailsave').button("option", "disabled", true);
        if (intrnl) {
            $('.detailcancel').button("option", "label", "Back to User");
        } else {
            $('.detailcancel').button("option", "label", "Back");
        }
//                frmvisualvalid = $('#frmuserdetails').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
//                $('#frmuserdetails').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
    };
    postSave = function() {
        $('.detailadd').button("option", "disabled", true);
        $('.detailsave').button("option", "disabled", true);
        if (intrnl) {
            $('.detailcancel').button("option", "label", "Back to User");
        } else {
            $('.detailcancel').button("option", "label", "Back");
        }
    };


    //ADVANCED SEARCH
    var nparams = { andor: '&&', items: [] }
    var advser = $("#advancedsearch").advSearch({
        colNames: [
            { disp: "Address1", valu: "Address1", typ: "str", srchop: [] }, { disp: "Address2", valu: "Address2", typ: "str", srchop: [] }, { disp: "City", valu: "City", typ: "str", srchop: [] }, { disp: "Country", valu: "Country", typ: "str", srchop: [] }, { disp: "Created By", valu: "CreatedBy", typ: "str", srchop: [] }, { disp: "Created Date", valu: "dtCreatedDate", typ: "date", srchop: [] }, { disp: "Display Name", valu: "DisplayName", typ: "str", srchop: [] }, { disp: "Email", valu: "Email", typ: "str", srchop: [] }, { disp: "First Name", valu: "FirstName", typ: "str", srchop: [] }, { disp: "Last Name", valu: "LastName", typ: "str", srchop: [] }, { disp: "Phone1", valu: "Phone1", typ: "str", srchop: [] }, { disp: "Phone2", valu: "Phone2", typ: "str", srchop: [] }, { disp: "PostalCode", valu: "PostalCode", typ: "str", srchop: [] }, { disp: "Role", valu: "ClientRoleName", typ: "str", srchop: [] }, { disp: "State", valu: "StateProv", typ: "str", srchop: [] }, { disp: "Title", valu: "Title", typ: "str", srchop: [] }
        ],
        params: nparams
    });
    
    SetSearchParams = function(params) {
        if (params != null) {
            advser[0].p.params = params;
            for (var i = 0; i < params.items.length; i++) {
                jQuery("#advancedsearch").addRow(params.items[i]);
            }
            if (params.items.length == 0) {
                jQuery("#advancedsearch").addRow();
            }
        } else {
            jQuery("#advancedsearch").addRow();
        }
    };
    
        //MAIN GRID
    function getData(pdata) {
        var hidsearchid = $('#hidsearchid').val();
        //var hidsearchid = $('#txtSid').val();
        if (overridepage > 0) {
            pdata.page = overridepage;
        }

        if (advser[0].p.params.items.length > 0) {
            paramstring = '{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:' + JSON.stringify(advser[0].p.params) + '}';
        } else {
            paramstring = '{seid:"' + hidsearchid + '", json:' + JSON.stringify(pdata) + ', search:null}';
        }
        //paramstring = JSON.stringify(params);
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Service/Services.aspx/Users",
            data: paramstring,
            dataType: "json",
            success: function(data, textStatus) {
                if (textStatus == "success") {
                    var thegrid = $("#list")[0];
                    thegrid.addJSONData(jQuery.parseJSON(data.d));
                }
            },
            error: function(data, textStatus) {
                //alert('An error has occured retrieving data!');
            }
        });
    };

    fillClientRoles = function(curval) {
        $('#user_role').html('');
        var urhtml = '';
        var dropdownResponse = FillDropdown("UserRoles");

        $.each(dropdownResponse, function(item) {
            urhtml += "<option value='" + dropdownResponse[item] + "' ";
            if (curval == dropdownResponse[item]) {
                urhtml += "selected";
            }
            urhtml += " >" + dropdownResponse[item] + "</option>";
        });
        $('#user_role').html(urhtml);
    },    
    GetSelectedItem = function(key, isinternal) {
        intrnl = isinternal;
        from_outside = true;
        var hidsearchid = $('#hidsearchid').val();
        //var hidsearchid = $('#txtSid').val();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Service/Services.aspx/SelectUser",
            data: '{seid:"' + hidsearchid + '", id:"' + key + '", intrnl:' + intrnl + '}',
            dataType: "json",
            success: function(data, textStatus) {
                $('#loaderwrapper').show();
                if (textStatus == "success") {
                    var custrow = jQuery.parseJSON(data.d);
                    if (custrow != null) {
                        ShowDetail();
                        FillUserForm(custrow);
                    }
                }
                $('#loaderwrapper').hide();
            },
            error: function(data, textStatus) {
                alert('An error has occured retrieving data!');
                $('#loaderwrapper').hide();
            }
        });
    };

    CreateGrid = function() {
        $('#list').jqGrid({
            datatype: function(pdata) {
                $('#loaderwrapper').show();
                getData(pdata);
            },
            jsonReader: {
                root: "rows", //arry containing actual data
                page: "page", //current page
                total: "total", //total pages for the query
                records: "records", //total number of records
                repeatitems: false
                //id: "FullName" //index of the column with the PK in it
            },
            colNames: columnNames,
            colModel: columnModel,
            rowNum: 15,
            rowList: [5, 10, 15, 20, 25, 30, 35, 40, 50],
            pager: jQuery('#pager'),
            gridview: false,
            hidegrid: false,
            onPaging: function() {
                resizeGrid();
            },
            resizeStop: function(newwidth, index) {
                //jqgrid is forcing me to jump thru alot of hoops just to allow me to resize the column and then resize the grid.
                //this is an ugly solution, but after 4 hours of cranking away at this, this is the best I can do.  
                var pg = $("#list").getGridParam('page');
                overridepage = pg;
                columnModel[index - 1].width = newwidth;
                columnModel[index - 1].widthOrg = newwidth;
                SetVCConfig();
                $("#list").jqGrid('GridUnload');
                $("#list").jqGrid('GridDestroy');
                CreateGrid();
                $("#list").trigger("reloadGrid");
                overridepage = 0;
            },
            onSelectAll: function(rowIdxArray, sts) {
            },
            onSelectRow: function(rowId) {
                $("#cb_list").removeAttr("checked");
            },
            gridComplete: function() {
                var grid = jQuery("#list");
                var ids = grid.jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var rowId = ids[i];
                    var editbutton = "<img src='/images/edit18.png' alt='chart' title='' class='gridButton' onclick=\"EditUser(" + rowId + ");\" />";
                    grid.jqGrid('setRowData', rowId, { Edit: editbutton });
                    if (i % 2 !== 0) {
                        var t = $("#" + rowId, grid);
                        t.addClass('alternateRow');
                    }
                }
                resizeGrid();
            },
            multiselect: true,
            rownumbers: false,
            sortname: 'Lastname',
            sortorder: 'desc',
            viewrecords: true,
            imgpath: '/CSS/themes/neopost/images',
            caption: '',
            width: '100%',
            height: '100%',
            sortable: true
        }).navGrid('#pager', { edit: false, add: false, del: false, refresh: false, view: false, search: false }, {}, {}, {}, { multipleSearch: true, overlay: false })
        $('#list').jqGrid('filterToolbar', { autosearch: true, searchOnEnter: false });

        $("#gbox_list").bind("sortstop", function(event, ui) {
            // you can even get the current permutation!
            // Yes, it looks like you may be grabbing the remapColumns function.
            //    You're not, you get an array of integers back.
            if (ui.item[0].id != 'list_Edit') {
                grid.jqGrid("getGridParam", "remapColumns");
                SetVCConfig();
            }
            var pg = $("#list").getGridParam('page');
            overridepage = pg;
            GetVCConfig();
            $("#list").jqGrid('GridUnload');
            $("#list").jqGrid('GridDestroy');
            CreateGrid();
            $("#list").trigger("reloadGrid");
            overridepage = 0;

        });

    };
    
    PageFilter();

});
